package com.example.quiz.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import android.util.Base64;
import android.util.Log;

public class HttpManager {
	
	public static String getData(PacoteRequisicao pacote){
		
		BufferedReader reader = null;
		String uri = pacote.getUri();
		if(pacote.getMethod().equals("GET")){
			uri += "?" + pacote.getParametrosCodificados();
		}
		try {
			URL url = new URL(uri);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod(pacote.getMethod());
						
			JSONObject json = new JSONObject(pacote.getparametros());			
			
			String parametros = json.toString();			
			
			if(pacote.getMethod().equals("POST")){
				con.setDoOutput(true);
				OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
				writer.write(parametros);
				writer.flush();
			}
			
			StringBuilder sb = new StringBuilder();
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			
			String line;
			
			while((line = reader.readLine()) != null){
				sb.append(line);
			}
			
			return sb.toString();
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally{
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
					return null;
				}
			}
		}
		
	}
	
	public static String getData(String uri, String userName, String password){
			
		BufferedReader reader = null;
		HttpURLConnection con = null;
		
		byte[] loginBytes = (userName +":"+password).getBytes();
		StringBuilder loginBuilder = new StringBuilder().append("Basic ").append(Base64.encodeToString(loginBytes, Base64.DEFAULT));
		
		try {
			URL url = new URL(uri);
			con = (HttpURLConnection) url.openConnection();
			
			con.addRequestProperty("Authorization", loginBuilder.toString());
			
			StringBuilder sb = new StringBuilder();
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			
			String line;
			
			while((line = reader.readLine()) != null){
				sb.append(line);
			}
			
			return sb.toString();
			
		} catch (Exception e) {
			e.printStackTrace();
			try {
				int status = con.getResponseCode();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return null;
		} finally{
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
					return null;
				}
			}
		}
		
	}

	
}
